<template>
  <div>父传子实现瀑布流</div>
  <div class="wrap">
    <div
      class="waterImg"
      v-for="(item, index) in renderWaterList"
      :key="index"
      :style="{
        height: item.height + 'px',
        background: item.background,
        left: item.left + 'px',
        top: item.top + 'px'
      }"
    >
      图片
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue';
// 接受父传子的 waterFallList
const props = defineProps<{
  waterFallList: object[];
}>();
// 定义渲染列表
const renderWaterList = reactive<any[]>([]);

const init = () => {
  // 获取当前屏幕宽度，计算一行可以放几列
  const x = document.body.clientWidth; // 获取的是文档实际内容区域的宽度，不包括滚动条
  // const x = window.innerWidth; // 获取的是浏览器窗口的宽度，包括垂直滚动条
  const width = 130;
  const colum = Math.floor(x / width);
  const heightList: any[] = []; // 临时存放图片渲染每列时候的高度
  for (let i = 0; i < props.waterFallList.length; i++) {
    if (i < colum) {
      renderWaterList.push(props.waterFallList[i]);
      renderWaterList[i].left = i * 130; // 计算图片 left
      // 将每列的高度存进heightList
      heightList.push(renderWaterList[i].height + 10); // 10为margin-bottom值
    } else {
      renderWaterList.push(props.waterFallList[i]);
      // 计算 left
      let index = 0;
      let min = heightList[0];
      for (let i = 0; i < heightList.length; i++) {
        if (min > heightList[i]) {
          index = i;
        }
      }
      renderWaterList[i].left = index * 130;
      // 计算 top
      renderWaterList[i].top = heightList[index] + 10;
      // 更新 heightList
      heightList[index] = renderWaterList[i].height + heightList[index] + 10;
    }
  }
};

onMounted(() => {
  window.onresize = () => init();
  init();
});
</script>

<style lang="scss" scoped>
.wrap {
  position: relative;
  .waterImg {
    position: absolute;
    width: 120px;
    margin: 0 10px 10px 0;
  }
}
</style>
